<template>
  <PageCard title="翻译工具">
    <div class="translation-container">
        <div class="input-section">
          <div class="language-selector">
            <n-select
              v-model:value="sourceLanguage"
              :options="sourceLanguageOptions"
              placeholder="源语言"
              class="language-select"
            />
            <n-button
              quaternary
              circle
              @click="swapLanguages"
              :disabled="sourceLanguage === 'auto'"
              class="swap-button"
            >
              <template #icon>
                <n-icon>
                  <svg viewBox="0 0 24 24">
                    <path fill="currentColor" d="M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z"/>
                  </svg>
                </n-icon>
              </template>
            </n-button>
            <n-select
              v-model:value="targetLanguage"
              :options="targetLanguageOptions"
              placeholder="目标语言"
              class="language-select"
            />
          </div>
          <n-input
            v-model:value="inputText"
            type="textarea"
            placeholder="请输入要翻译的文本..."
            :rows="8"
            class="input-textarea"
            @input="handleInput"
          />
          <div class="action-buttons">
            <n-button
              type="primary"
              @click="translate"
              :loading="loading"
              :disabled="!inputText.trim()"
            >
              翻译
            </n-button>
            <n-button
              @click="clearAll"
              :disabled="!inputText && !translatedText"
            >
              清空
            </n-button>
          </div>
        </div>

        <n-divider vertical class="divider-desktop" />
        <n-divider class="divider-mobile" />

        <div class="output-section">
          <div class="output-header">
            <span>翻译结果</span>
            <n-button
              v-if="translatedText"
              text
              @click="copyTranslation"
              class="copy-button"
            >
              <template #icon>
                <n-icon>
                  <svg viewBox="0 0 24 24">
                    <path fill="currentColor" d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
                  </svg>
                </n-icon>
              </template>
              复制
            </n-button>
          </div>
          <n-spin :show="loading">
            <div class="output-content">
              <div v-if="translatedText" class="translated-text">
                {{ translatedText }}
              </div>
              <div v-else class="placeholder-text">
                翻译结果将显示在这里
              </div>
            </div>
          </n-spin>
        </div>
      </div>

      <n-alert
        v-if="error"
        type="error"
        closable
        @close="error = ''"
        class="error-alert"
      >
        {{ error }}
      </n-alert>
    <n-divider />
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { NInput, NButton, NSelect, NIcon, NDivider, NSpin, NAlert, useMessage } from 'naive-ui'
import PageCard from '@/components/PageCard.vue'
import UsageGuide from '@/components/UsageGuide.vue'
import { TranslationApi } from '@/api/translation/TranslationApi'
import { SSEClient } from '@/utils/sse'

const message = useMessage()

const inputText = ref('')
const translatedText = ref('')
const sourceLanguage = ref('auto')
const targetLanguage = ref('中文')
const loading = ref(false)
const error = ref('')

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '选择源语言（支持自动检测）和目标语言',
    '在左侧输入框中输入要翻译的文本',
    '点击翻译按钮或输入后自动翻译',
    '翻译结果显示在右侧，可点击复制'
  ],
  tips: [
    '支持多种语言互译，包括中文、英文、日文、韩文等',
    '自动检测功能可智能识别输入语言',
    '点击中间交换按钮可快速切换翻译方向',
    '支持批量文本翻译，保留原文格式'
  ],
  example: '输入\'Hello World\'，选择英译中，得到\'你好世界\''
}

const sourceLanguageOptions = [
  { label: '自动检测', value: 'auto' },
  { label: '中文', value: '中文' },
  { label: 'English', value: 'English' },
  { label: '日本語', value: '日本語' },
  { label: '한국어', value: '한국어' },
  { label: 'Español', value: 'Español' },
  { label: 'Français', value: 'Français' },
  { label: 'Deutsch', value: 'Deutsch' },
  { label: 'Русский', value: 'Русский' },
  { label: 'Português', value: 'Português' },
  { label: 'Italiano', value: 'Italiano' }
]

const targetLanguageOptions = sourceLanguageOptions.filter(opt => opt.value !== 'auto')

const handleInput = () => {
  error.value = ''
}

const swapLanguages = () => {
  if (sourceLanguage.value === 'auto') return

  const temp = sourceLanguage.value
  sourceLanguage.value = targetLanguage.value
  targetLanguage.value = temp

  if (translatedText.value) {
    inputText.value = translatedText.value
    translatedText.value = ''
  }
}

const translate = async () => {
  if (!inputText.value.trim()) return

  loading.value = true
  error.value = ''

  try {
    const reader = await TranslationApi.translate({
      content: inputText.value,
      sourceLanguage: sourceLanguage.value,
      targetLanguage: targetLanguage.value
    })

    await SSEClient.processStream(reader, {
      targetRef: translatedText,
      clearBeforeStart: true,
      onError: (err) => {
        error.value = err.message || '翻译失败，请稍后重试'
      }
    })
  } catch (err: any) {
    error.value = err.message || '翻译失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const clearAll = () => {
  inputText.value = ''
  translatedText.value = ''
  error.value = ''
}

const copyTranslation = async () => {
  try {
    await navigator.clipboard.writeText(translatedText.value)
    message.success('已复制到剪贴板')
  } catch {
    message.error('复制失败')
  }
}
</script>

<style scoped lang="less">
.translation-container {
  display: flex;
  gap: 24px;
  min-height: 400px;

  @media (max-width: 768px) {
    flex-direction: column;
    gap: 16px;
  }
}

.input-section,
.output-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.language-selector {
  display: flex;
  align-items: center;
  gap: 12px;

  .language-select {
    flex: 1;
  }

  .swap-button {
    flex-shrink: 0;
  }
}

.input-textarea {
  flex: 1;
}



.divider-desktop {
  height: auto;

  @media (max-width: 768px) {
    display: none;
  }
}

.divider-mobile {
  display: none;

  @media (max-width: 768px) {
    display: block;
    margin: 0;
  }
}

.output-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.output-content {
  flex: 1;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
  min-height: 200px;

  @media (prefers-color-scheme: dark) {
    background: rgba(255, 255, 255, 0.05);
  }
}

.translated-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.placeholder-text {
  color: #999;
  text-align: center;
  padding: 40px 20px;
}

.error-alert {
  margin-top: 16px;
}

.copy-button {
  padding: 4px 8px;

  &:hover {
    color: var(--primary-color);
  }
}
</style>
